package ip

import (
	"fmt"
	"github.com/lionsoul2014/ip2region/binding/golang/xdb"
	"strings"
	"time"
)

var (
	dbPath string = "/root/hanlinyuan-qa/ip/ip2region.xdb"
	cBuff  []byte
)

func InitIpLocation() {
	var err error
	cBuff, err = xdb.LoadContentFromFile(dbPath)
	if err != nil {
		fmt.Printf("加载IP地址数据库失败 `%s`: %s\n", dbPath, err)
		return
	} else {
		fmt.Printf("加载IP地址数据库成功")
	}
}

func GetIpLocation(ip string) string {
	searcher, err := xdb.NewWithBuffer(cBuff)
	if err != nil {
		fmt.Printf("无法搜索: %s\n", err.Error())
		return ""
	}
	defer searcher.Close()
	var tStart = time.Now()
	region, err := searcher.SearchByStr(ip)
	if err != nil {
		fmt.Printf("无法搜索(%s): %s\n", ip, err)
		return ""
	}
	region = strings.Replace(region, "中国|0|", "", -1)
	fmt.Printf("区域: %s, 耗时: %s\n", region, time.Since(tStart))
	return region
}
